package com.xiaochen.manager.controller;

import com.xiaochen.manager.service.SysMenuService;
import com.xiaochen.manager.service.SysUserService;
import com.xiaochen.manager.service.ValidateCodeService;
import com.xiaochen.model.dto.system.LoginDto;
import com.xiaochen.model.entity.system.SysUser;
import com.xiaochen.model.vo.common.Result;
import com.xiaochen.model.vo.common.ResultCodeEnum;
import com.xiaochen.model.vo.system.LoginVo;
import com.xiaochen.model.vo.system.SysMenuVo;
import com.xiaochen.model.vo.system.ValidateCodeVo;
import com.xiaochen.utils.AuthContextUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统入口
 */
@Slf4j
@Tag(name = "用户接口")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 生成图片验证
     */
    @GetMapping("/generateValidateCode")
    public Result<ValidateCodeVo> generateValidateCode(){
        ValidateCodeVo validateCodeVo = validateCodeService.generateValidateCode();
        return Result.build(validateCodeVo, ResultCodeEnum.SUCCESS);
    }

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
        LoginVo loginVo = sysUserService.login(loginDto);
        return Result.build(loginVo, ResultCodeEnum.SUCCESS);
    }

    /**
     * 获取当前登录的用户信息(优化后)
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        // 1.直接从ThreadLocal里面获取用户信息
        SysUser sysUser = AuthContextUtil.get();
        // 2.返回用户信息
        return Result.build(sysUser, ResultCodeEnum.SUCCESS);
    }


//    /**
//     * 获取当前登录的用户信息
//     */
//    @GetMapping("/getUserInfo")
//    public Result getUserInfo(@RequestHeader(name = "token") String token){
//        // 1.从请求头里面获得token
//        // String token = request.getHeader("token");
//        // 2.根据token从redis里面获取用户信息
//        SysUser sysUser = sysUserService.getUserInfo(token);
//        // 3.返回用户信息
//        return Result.build(sysUser, ResultCodeEnum.SUCCESS);
//    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public Result logout(@RequestHeader(name = "token") String token){
        sysUserService.logout(token);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    // 查询用户可以操作的菜单
    @GetMapping("/findMenusByUserId")
    public Result findMenusByUserId(){
        List<SysMenuVo> list = sysMenuService.findMenusByUserId();
        return Result.build(list, ResultCodeEnum.SUCCESS);
    }
}
